/*
 * Demoiselle Framework
 * Copyright (C) 2011 SERPRO
 * ----------------------------------------------------------------------------
 * This file is part of Demoiselle Framework.
 * 
 * Demoiselle Framework is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2
 * as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not,  see <http://www.gnu.org/licenses/>
 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA  02110-1301, USA.
 * ----------------------------------------------------------------------------
 * Este arquivo é parte do Framework Demoiselle.
 * 
 * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou
 * modificá-lo dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação
 * do Software Livre (FSF); na versão 2 da Licença.
 * 
 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL em português
 * para maiores detalhes.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
 * "LICENCA.txt", junto com esse programa. Se não, acesse o Portal do Software Público
 * Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a Fundação do Software
 * Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
 
 * @author Tarcizio Vieira Neto (tarcizio.vieira@owasp.org) <a href="http://www.serpro.gov.br">SERPRO</a>
 * @created 2011
 */
package br.gov.frameworkdemoiselle.security.filter.accesscontrol;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.owasp.appsensor.APPSENSOR;
import org.owasp.appsensor.AppSensorServiceController;
import org.owasp.esapi.StringUtilities;

/**
 * This class was based on org.owasp.appsensor.filters.AppSensorRequestBlockingFilter 
 * from OWASP AppSensor
 * 
 * This class is a servlet filter that can be configured in the web.xml to 
 * provide default handling of blocking requests that are managed by 
 * AppSensor.  
 * The configuration in web.xml should be setup like this.
 * 
 * <filter>
 *    	<filter-name>AppSensorRequestBlockingFilter</filter-name>
 *    	<filter-class>
 *			br.gov.frameworkdemoiselle.security.filter.accesscontrol.AppSensorRequestBlockingFilter
 *		</filter-class>
 *    	<init-param>
 *     		<param-name>redirectURL</param-name>
 *     		<param-value>/errors/requestBlocked.jsp</param-value>
 *    	</init-param>
 * 	</filter>
 * 	<filter-mapping>
 *	    <filter-name>AppSensorRequestBlockingFilter</filter-name>
 *	    <url-pattern>/*</url-pattern>
 * 	</filter-mapping>
 * 
 * The "time" will be sent as a long to your configured page, and you can
 * then display this as you see fit
 */
public class AppSensorRequestBlockingFilter implements Filter {

	private String redirectURL = "appsensor_locked.jsp";
	
	/**
	 * Default constructor.
	 */
	public AppSensorRequestBlockingFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
	
		String requestURI = request.getRequestURI();
		
		//set on thread local so it's accessible later
		AppSensorServiceController.setCurrentRequestURI(requestURI);
		
		// is page disabled or active?
		boolean isActive = AppSensorServiceController.isServiceActive(requestURI);
		if (!(isActive)) {
			Long reactivation = AppSensorServiceController.getServiceReactivationTime(requestURI, APPSENSOR.asUtilities().getCurrentUser());
			response.sendRedirect(redirectURL + "?time=" + reactivation);
			// important: can't add chain.dofilter here. else, blocking by appsensor is negated
		} else { 
			// send the user to the page
			chain.doFilter(req, res);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.redirectURL = StringUtilities.replaceNull( filterConfig.getInitParameter( "redirectURL" ), redirectURL );
	}

}